package com.iie.bigVideo.service.impl;

import com.iie.bigVideo.entity.*;
import com.iie.bigVideo.entity.dto.AnnexDto;
import com.iie.bigVideo.entity.dto.ImageDto;
import com.iie.bigVideo.mapper.AnnexImgMapper;
import com.iie.bigVideo.mapper.AnnexMapper;
import com.iie.bigVideo.mapper.ImageMapper;
import com.iie.bigVideo.mapper.VideoMapper;
import com.iie.bigVideo.service.AnnexService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iie.bigVideo.utils.PageUtils;
import com.iie.bigVideo.utils.ResultUtils;
import com.iie.bigVideo.utils.UUIDUtils;
import com.iie.bigVideo.vo.ResultVO;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.ws.Action;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author XXX
 * @since 2024-01-30
 */
@Service
public class AnnexServiceImpl extends ServiceImpl<AnnexMapper, Annex> implements AnnexService {
    @Value("${server.port}")
    private String POST; //获取主机端口
    //相对路径
//    String property = System.getProperty("user.dir");
    @Value("${file.uploadFile}")
    private String uploadFile;
    @Value("${file.uploadFolder}")
    private String uploadFolder; // 静态资源实际存储路径
    @Value("${file.uploadFolderMysql}")
    private String uploadFolderMysql; //给数据库存的路径
    @Value("${file.uploadImage}")
    private String uploadImage; // 实际存储图片路径
    @Value("${file.uploadVideo}")
    private String uploadVideo; // 实际存储视频路径
    @Autowired
    private AnnexMapper annexMapper;
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private ImageMapper imageMapper;
    @Autowired
    private AnnexImgMapper annexImgMapper;

    @Override
    public ResultVO queryAnnexList(HashMap<String, String> hashMap) {
        if (hashMap == null) {
            return ResultUtils.error(500, "false", "服务器异常！");
        }
        Integer count = annexMapper.countAnnex();
        if (count == null || count == 0) {
            return ResultUtils.success(null); // 如果没有记录，则无需查询
        }
        int current = Integer.parseInt(hashMap.get("current"));
        int size = Integer.parseInt(hashMap.get("size"));
//        String sort = hashMap.get("sort");//排序标志
        // 计算当前页的起始索引
        int start = (current - 1) * size;
//        int sortInt = sort == null || sort.equals("0") ? 0 : Integer.parseInt(sort);//默认排序为0
        List<AnnexDto> annexListPage = annexDtoListObj(annexMapper.queryAnnexList(start, size, hashMap));
        // 计算总页数
        int pageCount = (int) Math.ceil((double) count / size);
        if (annexListPage == null && annexListPage.size() <= 0) {
            return ResultUtils.error(201, "false", "无数据！");
        }
        // 创建并填充 PageUtils 对象
        PageUtils<AnnexDto> videoPageUtils = new PageUtils<>();
        videoPageUtils.setCount(count);
        videoPageUtils.setPageCount(pageCount);
        videoPageUtils.setList(annexListPage);
        return ResultUtils.success(videoPageUtils);
    }

    /**
     * 新增附件
     *
     * @param hashMap
     * @return
     */
    @Override
    public ResultVO addAnnexObject(Map<String, Object> hashMap) {
        ArrayList<Image> arrayList = new ArrayList<>();//图集
        if (hashMap == null || hashMap.isEmpty()) {
            return ResultUtils.error(500, "false", "服务器异常！");
        }
        Object annex = hashMap.get("annex");//附件对象
        Object videoImgMainFile = hashMap.get("videoImgMainFile");//视频封面图
        Object videoFile = hashMap.get("videoFile");//视频
        String imageName = (String) hashMap.get("imageName");//图集名称
        Object imgMainFile = hashMap.get("imgMainFile");//图集封面图
        List<ImageDto> imgFile = (List<ImageDto>) hashMap.get("imgFile");//图集
        Video video = new Video();//视频
        Image image = new Image();//图集
        AnnexImg annexImg = new AnnexImg();//附件图集
        if (videoImgMainFile != null || videoFile != null) {
            boolean z = false; //状态
            MultipartFile newVideoImgMainFile = (MultipartFile) videoImgMainFile;//转换
            //视频封面图
            if (newVideoImgMainFile != null && !newVideoImgMainFile.isEmpty()) {
                //进行上传
                String uploadImgFilePath = uploadFile(newVideoImgMainFile);
                video.setVideoMainImg(uploadFolderMysql + uploadImage + uploadImgFilePath);
                z = true;
            }
            MultipartFile newVideoFile = (MultipartFile) videoFile;//转换
            //视频
            if (newVideoFile != null && !newVideoFile.isEmpty()) {
                //进行上传
                String uploadVideoFilePath = uploadFile(newVideoFile);
                video.setVideoUrl(uploadFolderMysql + uploadVideo + uploadVideoFilePath);
                z = true;
            }
            if (z) {
                //添加视频信息
                video.setVideoCreatedTime(new Date());//创建时间
                video.setVideoUpdatedTime(new Date());//更新时间
                videoMapper.addVideoObject(video);
                Video videoObject = videoMapper.queryByVideoId(video.getVideoId());//根据添加完操作，返回的ID 进行查询，是否添加成功？
            }
        }
        if (imgMainFile != null || imgFile != null) {
            //图集封面图
            boolean imgMain = false;
            MultipartFile newImgMainFile = (MultipartFile) imgMainFile;//转换
            if (newImgMainFile != null && !newImgMainFile.isEmpty()) {
                //进行上传
                String uploadImgFilePath = uploadFile(newImgMainFile);
                image.setImageMainImg(uploadFolderMysql + uploadImage + uploadImgFilePath);
                //添加图集信息
                image.setImageName(imageName);//图集名称
                image.setImageOrder("1");//顺序为1是封面图
                image.setImageCreatedTime(new Date());//创建时间
                image.setImageUpdatedTime(new Date());//更新时间
                imageMapper.addImageObject(image);
                imgMain = true;
            }
            //图集
            if (imgFile != null && imgFile.size() > 0) {
                Image imageObject = new Image();
                if (imgMain) {
                    //有封面图了
                    Integer id = image.getId();
                    imageObject = imageMapper.queryByImageIdObject(String.valueOf(id));
                }
                //根据order属性从小到大排序；
                imgFile = imgFile.stream().sorted(Comparator.comparing(ImageDto::getImageOrder, Comparator.nullsFirst(String::compareTo))).collect(Collectors.toList());
                for (int i = 0; i < imgFile.size(); i++) {
                    if (i == 0 && imgMain) {
                        //有封面
                        //进行上传
                        MultipartFile newImgFile = (MultipartFile) imgFile.get(i).getImageFile();//转换
                        String uploadImgFilePath = uploadFile(newImgFile);//上传
                        imageObject.setImagePath(uploadFolderMysql + uploadImage + uploadImgFilePath);//图片路径
                        //单独进行修改
                        imageMapper.updateImageObj(imageObject);
                    } else {
                        Image imageObj = new Image();
                        //进行上传
                        MultipartFile newImgFile = (MultipartFile) imgFile.get(i).getImageFile();//转换
                        String uploadImgFilePath = uploadFile(newImgFile);//上传
                        imageObj.setImagePath(uploadFolderMysql + uploadImage + uploadImgFilePath);//图片路径
                        imageObj.setImageOrder(imgFile.get(i).getImageOrder());//图片顺序
                        if (imgFile.get(i).getImageOrder().equals("1") && imageName != null) {
                            imageObj.setImageName(imageName);//图集名称
                        }
                        imageObj.setImageCreatedTime(new Date());
                        imageObj.setImageUpdatedTime(new Date());
                        //添加图集对象
                        arrayList.add(imageObj);
                    }
                }
            }
        }
        //添加附件信息
        Annex annexObj = (Annex) annex;
        if (video.getVideoId() != null) {
            annexObj.setVideoId(String.valueOf(video.getVideoId()));//视频ID
        }
        annexObj.setAnnexCreatedTime(new Date());//创建时间
        annexObj.setAnnexUpdatedTime(new Date());//更新时间
        annexMapper.addAnnexObject(annexObj);
        //添加附件图集信息
        if (image.getId() != null) {
            annexImg.setImageId(String.valueOf(image.getId()));//图片ID
            annexImg.setAnnexId(String.valueOf(annexObj.getId()));//附件ID
            annexImgMapper.addAnnexImgObject(annexImg);
        }
        //批量新增图集
        if (arrayList.size() > 0) {
//            //根据新增完的封面图，进行判断是否是修改了？还是新增了？
//            if (image.getId() != null) {
////                Integer imageSum = imageMapper.queryByImageId(String.valueOf(image.getId()));
//                String imagePath = arrayList.get(0).getImagePath();
//                imageMapper.updateByImageIdImagePath(image.getId(), imagePath);
//                arrayList.remove(0);//删除集合添加完的图片
//            }
            Integer integer = imageMapper.addImageList(arrayList);
            if (integer != null && integer > 0) {
                //新增中间表
                ResultVO resultVO = addAnnexImage(arrayList, annexObj.getId());
                if (resultVO.getData() == null) {
                    return ResultUtils.error(201, "false", resultVO.getDescription());
                }
            }
        }
        if (annexObj.getId() == null) {
            return ResultUtils.error(201, "false", "添加失败！");
        }
        return ResultUtils.success(annexObj);
    }

    /**
     * 删除附件
     *
     * @param annexId
     * @return
     */
    @Override
    public ResultVO deleteAnnex(int annexId) {
        Annex annex = annexMapper.queryAnnexObjectByAnnexId(annexId);
        if (annex == null) {
            return ResultUtils.error(201, "false", "无信息！");
        }
        //删除附件、删除附件下的视频、附件下的图集
        Integer integer = annexMapper.deleteAnnex(annex.getId());
        if (integer <= 0) {
            return ResultUtils.error(201, "false", "附件删除失败！");
        }
        //说明有附件
        if ((StringUtils.isNotBlank(annex.getVideoId()))) {
            //删除视频逻辑
            Video video = videoMapper.queryVideoObjectByVideoId(annex.getVideoId());//是否又此数据
            if (video != null) {
                //删除视频
                videoMapper.deleteVideo(Integer.parseInt(annex.getVideoId()));
                if (StringUtils.isNotBlank(video.getVideoMainImg()) && StringUtils.isNotBlank(video.getVideoUrl())) {
                    //有内容
                    //数据库视频信息删除成功了，开始删视频文件 和 图片了
                    deleteFile(uploadFile + video.getVideoUrl());//删除视频
                    deleteFile(uploadFile + video.getVideoMainImg());//删除图片
                } else if (StringUtils.isNotBlank(video.getVideoMainImg())) {
                    //只有图片
                    deleteFile(uploadFile + video.getVideoMainImg());//删除图片
                } else if (StringUtils.isNotBlank(video.getVideoUrl())) {
                    //只有视频
                    deleteFile(uploadFile + video.getVideoUrl());//删除视频
                }
            }
        }
        //删除图集逻辑
        List<AnnexImg> images = annexImgMapper.queryImgByAnnexId(String.valueOf(annex.getId()));//附件图片集
        if (images.size() > 0) {
            //说明有内容
            annexImgMapper.deleteAnnexImg(annex.getId());
            ArrayList<String> stringArrayList = new ArrayList<>();
            for (AnnexImg image : images) {
                stringArrayList.add(image.getImageId());
            }
            //删除图集
            List<Image> imageList = imageMapper.queryByImagesId(stringArrayList);
            if (imageList.size() > 0) {
                //说明有内容
                imageMapper.deleteByImagesId(stringArrayList); //逻辑删除
                //开始进行物理删除
                for (Image image : imageList) {
                    if (image.getImageMainImg() != null && StringUtils.isNotBlank(image.getImageMainImg())) {
                        deleteFile(uploadFile + image.getImageMainImg());//删除封面图片
                    }
                    //删除图集
                    if (image.getImagePath() != null && StringUtils.isNotBlank(image.getImagePath())) {
                        deleteFile(uploadFile + image.getImagePath());//删除图集
                    }
                }
            }
        }

        return ResultUtils.success(integer);
    }

    /**
     * 根据Id查询
     *
     * @param id
     * @return
     */
    @Override
    public ResultVO queryByAnnexId(int id) {
        if (id <= 0) {
            return ResultUtils.error(500, "false", "服务器异常！");
        }
        AnnexDto annexDto = annexMapper.queryByAnnexId(id);
        return ResultUtils.success(annexDto);
    }

    /**
     * 修改附件
     *
     * @param hashMap
     * @return
     */
    @Override
    public ResultVO updateAnnex(Map<String, Object> hashMap) {
        if (hashMap.isEmpty()) {
            return ResultUtils.error(500, "false", "服务器异常！");
        }
        Annex annex = (Annex) hashMap.get("annex");//附件
        Annex annexObj = annexMapper.queryAnnexObjectByAnnexId(annex.getId());
        if (hashMap.size() > 1) {
            //说明有要修改其他的内容
            MultipartFile videoImgMainFile = (MultipartFile) hashMap.get("videoImgMainFile");//视频封面
            MultipartFile videoFile = (MultipartFile) hashMap.get("videoFile");//视频
            MultipartFile imgMainFile = (MultipartFile) hashMap.get("imgMainFile");//图集封面
            List<ImageDto> imgFile = (List<ImageDto>) hashMap.get("imgFile");//图集
            String imageName = (String) hashMap.get("imageName");//图集名称
            //视频
            if (videoImgMainFile != null || videoFile != null) {
                String videoId = annexObj.getVideoId();//视频id
                Video video = videoMapper.queryVideoObjectByVideoId(videoId);//视频
                if (video != null) {
                    if (videoFile != null && !videoFile.isEmpty()) {
                        //上传视频
                        String uploadVideoFilePath = uploadFile(videoFile);
                        //物理删除原有的
                        if (StringUtils.isNotBlank(video.getVideoUrl())) {
                            deleteFile(uploadFile + video.getVideoUrl());
                        }
                        video.setVideoUrl(uploadFolderMysql + uploadVideo + uploadVideoFilePath);
                    }
                    //进行上传图片
                    if (videoImgMainFile != null && !videoImgMainFile.isEmpty()) {
                        String uploadImgFilePath = uploadFile(videoImgMainFile);
                        //物理删除原有的
                        if (StringUtils.isNotBlank(video.getVideoMainImg())) {
                            deleteFile(uploadFile + video.getVideoMainImg());
                        }
                        video.setVideoMainImg(uploadFolderMysql + uploadImage + uploadImgFilePath);
                    }
                    //修改视频信息
                    video.setVideoUpdatedTime(new Date());//更新时间
                    videoMapper.updateVideo(video);
                }
            }
            //图集封面 和 图集
            if (imgMainFile != null || imgFile != null) {
                List<AnnexImg> annexImgList = annexImgMapper.queryImgByAnnexId(String.valueOf(annex.getId()));
                if (annexImgList.size() > 0) {
                    ArrayList<String> arrayListImageId = new ArrayList<>();//图集id
                    for (AnnexImg image : annexImgList) {
                        arrayListImageId.add(image.getImageId());
                    }
                    //修改图集封面
                    if (imgMainFile != null && !imgMainFile.isEmpty()) {
                        List<Image> imageList = imageMapper.queryByImagesId(arrayListImageId);//图集
                        Image imageMain = new Image();//有封面的
                        for (int i = 0; i < imageList.size(); i++) {
                            if (imageList.get(i).getImageOrder().equals("1") || !imageList.get(i).getImageMainImg().isEmpty()) {
                                imageMain.setId(imageList.get(i).getId());
                                imageMain.setImageMainImg(imageList.get(i).getImageMainImg());
                                imageMain.setImageOrder(imageList.get(i).getImageOrder());
                                imageMain.setImagePath(imageList.get(i).getImagePath());
                                break;
                            }
                        }
                        //上传封面
                        String uploadImgMainFilePath = uploadFile(imgMainFile);
                        //物理删除原有的
                        if (StringUtils.isNotBlank(imageMain.getImageMainImg())) {
                            deleteFile(uploadFile + imageMain.getImageMainImg());
                        }
                        imageMain.setImageMainImg(uploadFolderMysql + uploadImage + uploadImgMainFilePath);
                        imageMain.setImageUpdatedTime(new Date());
                        imageMain.setImageName(imageName);//图集名称
                        imageMapper.updateImageObj(imageMain);//修改单个
                    }
                    //修改图集
                    if (imgFile != null && imgFile.size() > 0) {
                        //图集对象
                        ArrayList<Image> arrayImageList = new ArrayList<>();
                        //图集id
                        ArrayList<String> deleteImageId = new ArrayList<>();
                        MultipartFile imageObject = null;//上传的图集1
                        List<Image> imageList1 = imageMapper.queryByImagesId(arrayListImageId);//图集
                        for (int i = 0; i < imageList1.size(); i++) {
                            if (imageList1.get(i).getImageOrder().equals("1")) {
                                //有封面的
                                if (imgFile.get(i).getImageFile() != null) {
                                    //封面的图集
                                    //是文件
                                    imageObject = (MultipartFile) imgFile.get(i).getImageFile();
                                    //上传
                                    String uploadImgMainFilePath = uploadFile(imageObject);
                                    //物理删除原有的
                                    if (StringUtils.isNotBlank(imageList1.get(i).getImagePath())) {
                                        deleteFile(uploadFile + imageList1.get(i).getImagePath());
                                    }
                                    imageList1.get(i).setImageOrder(imgFile.get(i).getImageOrder());
                                    imageList1.get(i).setImagePath(uploadFolderMysql + uploadImage + uploadImgMainFilePath);
                                    imageList1.get(i).setImageCreatedTime(new Date());
                                    imageList1.get(i).setImageUpdatedTime(new Date());
                                    imageList1.get(i).setImageName(imageName);//图集名称
                                    arrayImageList.add(imageList1.get(i));//添加到新的集合中
                                    imgFile.remove(i);//删除文件的
                                }
                            } else {
                                if (StringUtils.isNotBlank(imageList1.get(i).getImagePath())) {
                                    deleteFile(uploadFile + imageList1.get(i).getImagePath());
                                }
                            }
                            deleteImageId.add((String.valueOf(imageList1.get(i).getId())));//保存数据库查询出的id
                        }
                        if (imgFile.size() > 0) {
                            //说明还有
                            for (int i = 0; i < imgFile.size(); i++) {
                                Image image = new Image();//新图集对象
                                if (imgFile.get(i).getImageFile() != null) {
                                    //是文件
                                    imageObject = (MultipartFile) imgFile.get(i).getImageFile();
                                    //上传
                                    String uploadImgMainFilePath = uploadFile(imageObject);
                                    image.setImagePath(uploadFolderMysql + uploadImage + uploadImgMainFilePath);//图集路径
                                    image.setImageOrder(imgFile.get(i).getImageOrder());//顺序
                                    image.setImageCreatedTime(new Date());
                                    image.setImageUpdatedTime(new Date());
                                    arrayImageList.add(image);
                                }
                            }
                        }
                        //新增图集全部内容
                        if (arrayImageList.size() > 0) {
                            Integer integer = imageMapper.addImageList(arrayImageList);
                            if (integer != null && integer > 0) {
                                //图集
                                imageMapper.deleteByImagesId(deleteImageId);//删除
                                //新增中间表
                                ResultVO resultVO = addAnnexImage(arrayImageList, annex.getId());
                                if (resultVO.getData() == null) {
                                    return ResultUtils.error(201, "false", resultVO.getDescription());
                                } else {
                                    //图集中间表
                                    annexImgMapper.deleteByImagesId(deleteImageId);//删除
                                }
                            }

                        }
                    }

                }
            }
        }
        //无文件
        String imageName = (String) hashMap.get("imageName");//图集名称
        String imageId = (String) hashMap.get("imageId");//图集id
        Image image = new Image();
        image.setId(Integer.parseInt(imageId));
        image.setImageName(imageName);
        imageMapper.updateImageObj(image);//修改图集信息
        Boolean aBoolean = annexMapper.updateAnnex(annex);//修改附件信息
        if (!aBoolean) {
            return ResultUtils.error(201, "false", "修改失败！");
        }
        return ResultUtils.success("修改成功！");
    }


    /**
     * 上传文件
     *
     * @return
     */
    public String uploadFile(MultipartFile file) {
        //校验上传的 是图片 还是 视频
        String contentType = file.getContentType();
        boolean image = contentType.startsWith("image");//如果是 image 开头 就是 图片
        String originalFilename = file.getOriginalFilename();//原文件名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));//扩展名
        String newFileName = "";
        try {
            if (image) {
                //图片
                //生成新的文件名
                newFileName = UUIDUtils.getUUID(16) + extension;
//                File fileObject = new File(Class.class.getClass().getResource("/").getPath() + uploadFolder + uploadImage);
                File fileObject = new File(uploadFolder + uploadImage);
                if (!fileObject.exists()) {
                    fileObject.mkdirs();//没有就创建
                }
                file.transferTo(new File(fileObject, newFileName));//对文件进行上传
            } else {
                //视频
                //生成新的文件名
                newFileName = UUIDUtils.getUUID(16) + extension;
//                File fileObject = new File(Class.class.getClass().getResource("/").getPath() + uploadFolder + uploadVideo);
                File fileObject = new File(uploadFolder + uploadVideo);
                if (!fileObject.exists()) {
                    fileObject.mkdirs();//没有就创建
                }
                file.transferTo(new File(fileObject, newFileName));//对文件进行上传
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return newFileName;
    }

    /**
     * 删除文件
     *
     * @return
     */
    public static Boolean deleteFile(String filePath) {
        File dir = new File(filePath);
        //isFile()判断是否是文件，exists()判断该文件是否存在，delete()删除成功返回1失败则返回0
        if (dir.isFile() && dir.exists() && dir.delete()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 新增中间表 附件 与 图集
     */
    public ResultVO addAnnexImage(ArrayList<Image> list, Integer annexId) {
        List<AnnexImg> annexImgList = new ArrayList<>();
        int imageId = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getId() != null) {
                imageId = list.get(i).getId();//赋值一个
            }
            list.get(i).setId(imageId + i);//赋值 新增的id
            AnnexImg annexImg = new AnnexImg();
            annexImg.setAnnexId(String.valueOf(annexId));//附件ID
            annexImg.setImageId(String.valueOf(list.get(i).getId()));//图片id
            annexImgList.add(annexImg);
        }
        if (annexImgList.isEmpty()) {
            return ResultUtils.error(201, "false", "无数据！");
        }
        //批量插入数据库
        Integer integer = annexImgMapper.addAnnexImg(annexImgList);
        return ResultUtils.success(integer);
    }

    /**
     * 处理返回结果
     *
     * @return
     */
    private List<AnnexDto> annexDtoListObj(List<AnnexDto> annexDtoList) {
        if (annexDtoList.size() > 0) {
            //有内容
            for (AnnexDto annexDto : annexDtoList) {
                //图集
                //有图集
                List<Image> imageList = annexDto.getImageList();
                if (!imageList.isEmpty()) {
                    ArrayList<Image> imageArrayList = new ArrayList<>();
                    for (Image image : imageList) {
                        if (StringUtils.isNotBlank(image.getImageMainImg())) {
                            //有封面
                            imageArrayList.add(image);
                        }
                        imageArrayList.add(image);
                    }
                    annexDto.setImageList(imageArrayList);
                }

            }
        }
        return annexDtoList;
    }

}
